package org.snare.alumni.modules.app;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.snare.alumni.modules.admin.activity.dto.ActivityDTO;
import org.snare.alumni.modules.admin.activity.entity.ActivityEntity;
import org.snare.alumni.modules.admin.activity.entity.ActivityUserEntity;
import org.snare.alumni.modules.admin.activity.mapper.ActivityMapper;
import org.snare.alumni.modules.admin.activity.mapper.ActivityUserMapper;
import org.snare.alumni.modules.admin.activity.service.api.ActivityService;
import org.snare.alumni.modules.admin.card.service.api.CardService;
import org.snare.spider.toolkit.jwt.JwtUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api(tags = "校友活动")
@RequestMapping("/alumni/app/activity")
@RestController
@RequiredArgsConstructor
public class ActivityController {

    private final CardService cardService;

    private final ActivityService activityService;

    private final ActivityMapper activityMapper;

    private final ActivityUserMapper activityUserMapper;

    @GetMapping("/list")
    @ApiOperation(value = "列表", httpMethod = "GET")
    List<ActivityEntity> list() {
        return activityMapper.selectList(null);
    }

    @GetMapping("/detail")
    @ApiOperation(value = "详情", httpMethod = "GET")
    ActivityDTO detail(@RequestParam String id) {
        String uid = JwtUtils.getUid();
        ActivityDTO activityDTO = activityService.detail(id);
        Long count = new LambdaQueryChainWrapper<>(activityUserMapper).eq(ActivityUserEntity::getActivityId, id).count();
        Long myCount = new LambdaQueryChainWrapper<>(activityUserMapper)
                .eq(ActivityUserEntity::getActivityId, id)
                .eq(ActivityUserEntity::getUid, uid)
                .count();
        activityDTO.setPeopleNum(count);
        activityDTO.setHasSignUp(myCount == 1);
        return activityDTO;
    }

    @GetMapping("/signUp")
    @ApiOperation(value = "报名", httpMethod = "GET")
    void signUp(@RequestParam String id) {
        String uid = JwtUtils.getUid();
        if (!cardService.checkApply(uid)) {
            throw new RuntimeException("请先申请校友卡获取更多权益");
        }
        activityService.signUp(id, uid);
    }

}
